﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ArtClub.Model;

namespace ArtClub.DAL
{
    internal class AuctionDB : IAuctionDB
    {
        private ArtClubContext db = new ArtClubContext();

        public void Create(Auction auction)
        {
			int count = (from a in db.Auctions
						 where a.AuctionItem.Id == auction.AuctionItem.Id
						 select a).Count();

			if (count > 0)
				throw new Exception("That item has already been set up for auction.");

			// Don't add a new auction item row.
			db.Entry(auction.AuctionItem).State = System.Data.Entity.EntityState.Unchanged;

            db.Auctions.Add(auction);
            db.SaveChanges();
        }

        public Auction GetAuction(int id)
        {
            return (from a in db.Auctions.Include("Bids")
                    where a.Id == id
                    select a).SingleOrDefault();
        }

        public List<Auction> ListAuctions()
        {
            return (from m in db.Auctions.Include("AuctionItem").Include("Bids.Bidder")
                    select m).ToList();
        }

        public List<Auction> ListAuctionsBySold(bool isSold)
        {
            return (from a in db.Auctions
                    where a.Sold == isSold
                    select a).ToList();
        }

        public void Update(Auction auction, Bid bid)
        {
			// Get the auction.
			Auction getA = (from a in db.Auctions
							where a.Id == auction.Id
							select a).Single();

			// Don't add the member from the bid. (FAILS)
			db.Entry(bid.Bidder).State = System.Data.Entity.EntityState.Unchanged;

			// Add the to the auction.
			getA.Bids.Add(bid);

			// Save changes.
			db.SaveChanges();
        }

        public void Close(Auction auction)
        {
            Auction getA = (from a in db.Auctions
                            where a.Id == auction.Id
                            select a).Single();
            getA.Sold = true;

            db.SaveChanges();
        }
	}
}
